package com.leil.nio.scatteringGathering;


import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;

public class ScatteringGatheringDemo {

    public static void main(String[] args) {
        try {
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            InetSocketAddress address = new InetSocketAddress(7777);
            serverSocketChannel.bind(address);
            System.out.println("server start success on 7777");

            SocketChannel socketChannel = serverSocketChannel.accept();

            ByteBuffer[] buffers = new ByteBuffer[2];
            buffers[0] = ByteBuffer.allocate(5);
            buffers[1] = ByteBuffer.allocate(1024);

            while (true) {
                long read = socketChannel.read(buffers);
                if (read == -1) {
                    break;
                }
                Arrays.stream(buffers).forEach(buffer -> {
                    buffer.flip();
                });

                byte[] bytes1 = buffers[0].array();
                byte[] bytes2 = buffers[1].array();


                System.out.println(read);
                System.out.println(bytes1.length);
                System.out.println(bytes2.length);

                socketChannel.write(buffers);

                Arrays.stream(buffers).forEach(buffer -> {
                    buffer.clear();
                });


            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
